package com.hdu.xxl_job_client.client;


import com.hdu.xxl_job_client.config.XxlJobClientConfigProperties;
import lombok.extern.slf4j.Slf4j;
import lombok.val;
import org.apache.commons.httpclient.Cookie;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;

import static com.hdu.xxl_job_client.utils.SimpleHttpClient.getPostCookies;
import static java.util.Objects.isNull;

@Component
@Slf4j
public class LoginClient {

    private String COOKIE = "";
    private final XxlJobClientConfigProperties clientConfigProperties;

    public LoginClient(XxlJobClientConfigProperties clientConfigProperties) {
        this.clientConfigProperties = clientConfigProperties;
    }

    @PostConstruct
    public void init() {
        log.info("xxl JOB 初始化配置：{}", clientConfigProperties.toString());
        val cookies = getPostCookies(clientConfigProperties.getLoginUrl());
        if (isNull(cookies)) {
            log.error("xxlJob 登录失败");
        } else {
            val tmpCookies = new StringBuilder();
            for (Cookie c : cookies) {
                tmpCookies.append(c.toString()).append(";");
            }
            COOKIE = tmpCookies.toString();
            log.info("xxlJob 登录成功");
        }
    }

    public String getCOOKIE() {
        return COOKIE;
    }
}
